import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:wan_android/model/user/user_page_model.dart';

class LoginPage extends StatefulWidget {
  final String username;
  const LoginPage(this.username, {super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController _userController = TextEditingController();
  final TextEditingController _pwdController = TextEditingController();
  UserPageModel? _userPageModel;


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _userController.text = widget.username;

    final UserPageModel userPageModel = Provider.of<UserPageModel>(context, listen: false);
    setState(() {
      _userPageModel = userPageModel;
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _userController.dispose();
    super.dispose();
  }

  _showLoading() {
    showToastWidget(
      position: ToastPosition.center,
      const CircularProgressIndicator(
        backgroundColor: Colors.grey,
        color: Colors.white,
      )
    );
  }

  _closeLoading() {
    dismissAllToast();
  }

  _onLogin() async {
    String username = _userController.text;
    String password = _pwdController.text;
    await _userPageModel!.onLogin({'username': username, 'password': password});
    print('执行====');
    if (_userPageModel?.userInfo != null) {
      showToast(
        '登录成功',
        // duration: const Duration(seconds: 2),
        backgroundColor: Colors.greenAccent,
        position: ToastPosition.top,
      );
      // context.pop(true);
      // context.go('/index', extra: {'refresh': true});
      context.pop(true);
    } else {
      showToast(
        '登录异常,请检查账号密码是否正确',
        backgroundColor: Colors.redAccent,
        position: ToastPosition.top
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('登录', style: TextStyle(color: Colors.white)),
        backgroundColor: Colors.blueAccent,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: Stack(
        children: [
          ClipPath(
            clipper: HalfCircleClipper(),
            child: Container(
              height: 600.h,
              color: Colors.blueAccent,
            ),
          ),

          SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(height: 500.h),
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 40.w),
                  child: Card(
                    child: Padding(
                      padding: EdgeInsets.all(40.r),
                      child: Form(
                        key: _formKey,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Padding(
                              padding: EdgeInsets.symmetric(vertical: 20.h),
                              child: TextFormField(
                                controller: _userController,
                                decoration: const InputDecoration(
                                  prefixIcon: Icon(Icons.person_outline, color: Colors.blueAccent),
                                  hintText: '用户名'
                                ),
                                validator: (value) {
                                  if (value == null || value.isEmpty) {
                                    return '请输入用户名';
                                  }
                                  return null;
                                },
                              ),
                            ),
                            
                            Padding(
                              padding: EdgeInsets.symmetric(vertical: 20.h),
                              child: TextFormField(
                                controller: _pwdController,
                                decoration: const InputDecoration(
                                  prefixIcon: Icon(Icons.lock_outline, color: Colors.blueAccent),
                                  hintText: '密码'
                                ),
                                obscureText: true,
                                validator: (value) {
                                  if (value == null || value.isEmpty) {
                                    return '请输入密码';
                                  }
                                  return null;
                                },
                              ),
                            ),
                            
                            Padding(
                              padding: EdgeInsets.only(top: 30.h, bottom: 12.h),
                              child: SizedBox(
                                width: double.infinity,
                                height: 64.h,
                                child: ElevatedButton(
                                  style: ElevatedButton.styleFrom(
                                    backgroundColor: Colors.blueAccent
                                  ),
                                  child: const Text('登 录', style: TextStyle(color: Colors.white),),
                                  onPressed: () {
                                    if (_formKey.currentState!.validate()) {
                                      // context.pop();
                                      _onLogin();
                                    }
                                  },
                                ),
                              )
                            ),

                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                const Text('还没账号?'),
                                TextButton(
                                  child: const Text('去注册', style: TextStyle(color: Colors.blueAccent)),
                                  onPressed: () {
                                    final res = context.push('/sign_up');
                                    _userController.text = res as String;
                                  },
                                )
                              ],
                            )
                          ],
                        ),
                      ),
                    )
                  ),
                ),

                Padding(
                  padding: EdgeInsets.symmetric(vertical: 50.h),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      IconButton(
                        icon: const Icon(Icons.wechat_outlined, color: Colors.greenAccent,),
                        onPressed: () {
                          print('授权微信登录');
                        },
                      ),

                      IconButton(
                        icon: const Icon(Icons.apple, color: Colors.blueAccent),
                        onPressed: () {
                          print('授权微博登录');
                        }
                      )
                    ],
                  )
                )
              ],
            )
          ),
        ],
      ),
    );
  }
}


class HalfCircleClipper extends CustomClipper<Path> {

  @override
  Path getClip(Size size) {
    final path = Path();
    path.lineTo(0, size.height / 2); // 从左上角到左边中间
    path.quadraticBezierTo(
      size.width / 2, size.height, // 控制点
      size.width, size.height / 2 // 终点
    );
    path.lineTo(size.width, 0); // 从中间到右上角
    path.close(); // 闭合路径
    return path;
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) => false;
}